<template>
  <div>
    <!-- 1.发起axios请求，获取数据 -->
    <!-- 2.在MyTable中插入插槽 -->
    <!-- 3.利用v-if和v-else来控制input和button，自定义指令获取input聚焦，绑定focus事件失去焦点 -->
    <!-- 4.绑定键盘按下事件，v-model绑定值，然后push到数据中，，要进行非空判断，再清空数据 -->
    <!-- 5.利用数组的filter方法给删除数据 -->
    <MyTable :list="list">
      <template #head>
        <th>#</th>
        <th>商品名称</th>
        <th>价格</th>
        <th>标签</th>
        <th>操作</th>
      </template>
      <template #body="{ row }">
        <td>{{ row.id }}</td>
        <td>{{ row.goods_name }}</td>
        <td>{{ row.goods_price }}</td>
        <td>
          <input
            type="text"
            v-if="row.inputVisible"
            class="tag-input form-control"
            style="width: 100px"
            v-fff
            @blur="row.inputVisible = false"
            @keyup.enter="enterFn(row)"
            v-model="row.inputValue"
          />
          <button
            v-else
            @click="row.inputVisible = true"
            class="btn btn-primary btn-sm add-tag"
            style="display: block"
          >
            +Tags
          </button>
          <span
            v-for="(item, index) in row.tags"
            :key="index"
            class="badge badge-warning"
          >
            {{ item }}</span
          >
        </td>
        <td>
          <button class="btn btn-danger btn-sm" @click="deleFn(row.id)">
            删除
          </button>
        </td>
      </template>
    </MyTable>
  </div>
</template>

<script>
import MyTable from "../components/MyTable.vue";
export default {
  components: {
    MyTable,
  },
  data() {
    return {
      list: [],
    };
  },
  async created() {
    const { data: res } = await this.$axios.get("/api/goods");
    this.list = res.data;
  },
  directives: {
    fff: {
      inserted(el) {
        el.focus();
      },
    },
  },
  methods: {
    enterFn(row) {
      if (row.inputValue.trim() === "") return alert("请输入数据");
      //   row.inputValue = ""
      row.tags.push(row.inputValue);
      row.inputValue = "";
      row.inputVisible = false;
    },
    deleFn(id) {
      return (this.list = this.list.filter((item) => item.id !== id));
    },
  },
};
</script>

<style>
</style>